package com.xiangban.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiangban.dao.*;
import com.xiangban.exception.BizException;
import com.xiangban.model.*;
import com.xiangban.model.dto.AccompanyReceiveOrderDto;
import com.xiangban.model.dto.AccompanyReceiveStatusDto;
import com.xiangban.model.dto.HospitalDto;
import com.xiangban.model.dto.OrderDto;
import com.xiangban.model.res.ApiResult;
import com.xiangban.model.res.ApiResultCode;
import com.xiangban.service.InsuranceService;
import com.xiangban.service.OrderReceivingService;
import com.xiangban.service.PayService;
import com.xiangban.util.AmapUtil;
import com.xiangban.util.CommonUtil;
import com.xiangban.util.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xiangban.util.AesUtil.decrypt;
import static com.xiangban.util.AesUtil.encrypt;
import static com.xiangban.util.CommonUtil.BizEmpty;
import static com.xiangban.util.CommonUtil.getOrderNo;

/**
 * @Author ly
 * @date 2021/12/8 14:10
 */
@Service
@Slf4j
public class OrderReceivingServiceImpl implements OrderReceivingService {
    @Value("${distance.MI}")
    private Integer distance;
    private static String password = "xiangbanyilu";
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private PageUtils pageUtils;
    @Autowired
    private   CommonUtil commonUtil;
    @Autowired
    private TUserMappers tUserMappers;
    @Autowired
    private RelationMapper relationMapper;
    @Autowired
    private AccompanyReceiveStatusMapper accompanyReceiveStatusMapper;
    @Autowired
    private AccompanyReceiveOrderMapper accompanyReceiveOrderMapper;
    @Autowired
    private  AccompanyAwardOrderMapper accompanyAwardOrderMapper;
    @Autowired
    private AccompanyInviteMapper accompanyInviteMapper;
   @Autowired
   private AccompanyWalletMapper accompanyWalletMapper;
   @Autowired
   private AccompanyWalletRecodeMapper accompanyWalletRecodeMapper;
   @Autowired
   private OrderCommentMapper orderCommentMapper;

   @Autowired
   private AccompanyMapper accompanyMapper;
   @Autowired
   private  HospitalMapper hospitalMapper;

   @Autowired
   private PayService payService;
   @Autowired
   private InsuranceService insuranceService;
   @Autowired
   private InsuranceMapper insuranceMapper;
   @Value("${smsTemplate.UserSmsId}")
   private  String UserSmsId;

    /**
     * 等待接单
     */
    @Override
    public PageInfo<OrderDto> awaitOrderReceiving() {//陪诊id 为0 或者自己的  status 为2
        String userId = commonUtil.getUserId(request);
        List<OrderDto> orderDto = new ArrayList<>();
        if (userId.equals("")){
            orderDto=   orderMapper.getOrderNo();
            return new PageInfo<>(orderDto);
        }

        TUser tUser = new TUser();
        tUser.setUid(Integer.parseInt(userId));
        ApiResult<Object> userStatus = getUserStatus(tUser);
        UserAccompany dataMap = (UserAccompany) userStatus.getDataMap();
   if (BizEmpty(dataMap)){
       orderDto=   orderMapper.getOrderNo();
       return new PageInfo<>(orderDto);
   }

        //查询待接订单列表
        PageHelper.startPage(pageUtils.getPage().getPageNum(), pageUtils.getPage().getPageSize());
        OrderDto order = new OrderDto();
        if (!BizEmpty(dataMap)){
             order.setAccompanyId(dataMap.getAccompanyId());
        }
        order.setStatus(2);
         orderDto =orderMapper.getListAwaitOrder(order);
        return new PageInfo<>(orderDto);
    }

    /**
     * 已接订单
     * */
    @Override
    public PageInfo<OrderDto> alreadyOrderReceiving() {
        PageHelper.startPage(pageUtils.getPage().getPageNum(),pageUtils.getPage().getPageSize());
        String userId = commonUtil.getUserId(request);
        //根据uid查询是不是陪诊
        TUser tUser = new TUser();
        tUser.setUid(Integer.parseInt(userId));
        ApiResult<Object> userStatus = getUserStatus(tUser);
        UserAccompany dataMap = (UserAccompany)userStatus.getDataMap();
        List<OrderDto> ListorderDto = new ArrayList<>();
        if (BizEmpty(dataMap)){
            return new PageInfo<>(ListorderDto);
        }
        //根据陪诊id 去订单表查询所接订单
        Integer accompanyId = dataMap.getAccompanyId();
        Order order = new Order();
        order.setAccompanyId(accompanyId);
         ListorderDto = orderMapper.getListOrderByAid(order);
        return new PageInfo<>(ListorderDto);
    }
  /**
   * 订单确认
   * */
    @Override
    @Transactional
    public Object orderOk(Order order) {//orderid  //经纬度  //
        if (BizEmpty(order.getOrderNo())){
            throw new BizException(ApiResultCode.COMMON_PARAM_NULL);
        }
        if (BizEmpty(order.getStartLatitude())||BizEmpty(order.getStartLongitude())||BizEmpty(order.getStatus())){
            throw new BizException(ApiResultCode.COMMON_PARAM_NULL);
        }
      //根据orderid 查询 订单
        OrderDto orderByOrderNo = orderMapper.getOrderByOrderNo(order);
        if (BizEmpty(orderByOrderNo)){
            throw  new BizException(ApiResultCode.NOT_ORDER);
        }
        if (orderByOrderNo.getFailStatus()==1||orderByOrderNo.getFailStatus()==3){
            throw  new BizException(ApiResultCode.USER_REFUND);
        }
        String userId = commonUtil.getUserId(request);
        TUser tUser = new TUser();
        tUser.setUid(Integer.parseInt(userId));
        ApiResult<Object> userStatus = getUserStatuss(tUser);
        UserAccompany dataMap = (UserAccompany)userStatus.getDataMap();
        Integer accompanyId = dataMap.getAccompanyId();//当前我的陪诊id
        Integer accompanyId1 = orderByOrderNo.getAccompanyId();//指定的陪诊
        Integer status = order.getStatus();
        if (status==2&&accompanyId1==0){
            return "ok";
        }
        if (status==2&&accompanyId1.equals(accompanyId)){
            //指定的单子被拒绝  将陪诊id 换为 0
            order.setAccompanyId(accompanyId);
            order.setAccompanyStatus(2);
            orderMapper.updateAccompanyId(order);
            return "ok";
        }

        if (accompanyId1==0||accompanyId1.equals(accompanyId)){

            //并且这个订单不能被重复接单
          AccompanyReceiveOrder accompanyReceiveOrderinfo=  accompanyReceiveOrderMapper.getReceiveByOrderNo(orderByOrderNo);
           if (!BizEmpty(accompanyReceiveOrderinfo)){
               throw  new BizException(ApiResultCode.ALREADY_ORDER);
           }
           if (orderByOrderNo.getPayType()==5){

              orderByOrderNo.setAccompanyId(dataMap.getAccompanyId());
              orderByOrderNo.setStartLongitude(order.getStartLongitude());
              orderByOrderNo.setStartLatitude(order.getStartLatitude());
               //陪诊代付  微信支付
               Object o = payService.WxPay(orderByOrderNo);

               return o;
           }
            AccompanyAddWallet(dataMap,order,orderByOrderNo);
            //发送短信 根据订单编号 查询 患者手机号
            OrderDto relationPhoneByOrderNo = orderMapper.getRelationPhoneByOrderNo(order);
            if (!BizEmpty(relationPhoneByOrderNo.getPhone())){
                Map<String,Object> map = new HashMap<>();
                ApiResult<Object> send = payService.Send(relationPhoneByOrderNo.getPhone(),UserSmsId,map);
//                log.info(JSONObject.toJSONString(send)+">>>>>>>>>>>>");
            }

         return "ok";
        }

         else {
         throw new BizException(ApiResultCode.ASSIGN);
        }

    }

    public String AccompanyAddWallet(UserAccompany userAccompany1,Order order,OrderDto orderByOrderNo){
        Integer accompanyId = userAccompany1.getAccompanyId();
        order.setAccompanyId(accompanyId);
        order.setAccompanyStatus(1);
        orderMapper.updateAccompanyId(order);
        //生成 接单编号
        String receiveNo = getOrderNo();
        //讲订单编号和接单编号接单人绑定到一起
        AccompanyReceiveOrderDto accompanyReceiveOrderDto = new AccompanyReceiveOrderDto();
        accompanyReceiveOrderDto.setAccompanyId(accompanyId);
        accompanyReceiveOrderDto.setOrderNo(order.getOrderNo());
        accompanyReceiveOrderDto.setReceiveNo(receiveNo);
        accompanyReceiveOrderDto.setStatus(0);
        accompanyReceiveOrderDto.setLongitude(order.getStartLongitude());
        accompanyReceiveOrderDto.setLatitude(order.getStartLatitude());
        accompanyReceiveOrderMapper.insertBinding(accompanyReceiveOrderDto);
        accompanyReceiveStatusMapper.insertBinding(accompanyReceiveOrderDto);
        //查询此陪诊的加价价格
        BigDecimal unitPrice = userAccompany1.getUnitPrice();
        BigDecimal accompanyMoney = orderByOrderNo.getAccompanyMoney();
        //此订单超出价格
        BigDecimal exceed = orderByOrderNo.getExceed();
        BigDecimal exceed1 = exceed.divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP);//超出价格的一半
        BigDecimal add = unitPrice.add(accompanyMoney).add(exceed1);
        //修改order表的陪诊价格
        order.setAccompanyMoney(add);
        orderMapper.updateAccompanyMoney(order);
        //加钱包记录
        //根据陪诊id 找到钱包id
        AccompanyWallet accompanyWallet = new AccompanyWallet();
        accompanyWallet.setAccompanyId(accompanyId);
        AccompanyWallet moneySum = accompanyWalletMapper.getMoneySum(accompanyWallet);
        AccompanyWalletRecode accompanyWalletRecode = new AccompanyWalletRecode();
        accompanyWalletRecode.setWalletId(moneySum.getId());
        accompanyWalletRecode.setType(1);
        accompanyWalletRecode.setMoney(add);
        accompanyWalletRecode.setStatus(1);
        accompanyWalletRecode.setTransactionNo(receiveNo);
        accompanyWalletRecodeMapper.insertWalletByWalletId(accompanyWalletRecode);
        //给上级加钱
        //先看看上级有没有人
        UserAccompany userAccompany = new UserAccompany();
        userAccompany.setAccompanyId(accompanyId);
        UserAccompany accompanyByPid = accompanyMapper.getAccompanyByPid(userAccompany);
        AccompanyInvite accompanyInvite = new AccompanyInvite();
        accompanyInvite.setUid(accompanyByPid.getUid());
        AccompanyInvite accompanyAwardOrderInfo =  accompanyInviteMapper.getaccompanyPid(accompanyInvite);
        if (!BizEmpty(accompanyAwardOrderInfo)){
            AccompanyReceiveOrder  accompanyReceiveOrder = new AccompanyReceiveOrder();
            accompanyReceiveOrder.setAccompanyId(accompanyId);
            accompanyReceiveOrder.setOrderNo(order.getOrderNo());
            superiorOperate(accompanyAwardOrderInfo,accompanyReceiveOrder);
        }

        return "ok";

    }

    private ApiResult<Object> getUserStatuss(TUser tUser) {
        UserAccompany userAccompany = tUserMappers.getAccompanyInfoByUid(tUser);
         if (BizEmpty(userAccompany)){
             throw new BizException(ApiResultCode.NOT_ACCOMPANY);
         }
         if (userAccompany.getStatus()==1){
             throw new BizException(ApiResultCode.UNDER_REVIEW);
         }
         if (userAccompany.getStatus()==2){
             throw new BizException(ApiResultCode.AUDIT_FAILURE);
         }
         if (userAccompany.getWorkStatus()==1){
             throw new BizException(ApiResultCode.FREEZE);
         }
        return ApiResult.newSuccess(userAccompany);

    }

    /**
     * 订单详情
     * */
    @Override
    public Object orderDetails(Order order) throws Exception {//订单编号
           //根据订单编号查询出订单详情 服务对象 名字 手机号 接单状态
        OrderDto orderByOrderNo = orderMapper.getOrderInfoByOrderNo(order);

        //查询人名 电话
        Integer patientId = orderByOrderNo.getPatientId();
        Relation relation = new Relation();
        relation.setId(patientId);
        Relation familyByRelationId = relationMapper.getFamilyByRelationId(relation);
        String phone = familyByRelationId.getPhone();
        String name = familyByRelationId.getName();
        orderByOrderNo.setHospitalName(orderByOrderNo.getName());
        orderByOrderNo.setName(name);
        orderByOrderNo.setPhone(phone);
        //查询订单服务状态

       List<AccompanyReceiveStatusDto> accompanyReceiveStatus= accompanyReceiveStatusMapper.getStatusByOrderNo(order);
        orderByOrderNo.setAccompanyReceiveStatus(accompanyReceiveStatus);
    //将这些经纬度 换算成地址
         for (AccompanyReceiveStatusDto receiveStatus : accompanyReceiveStatus) {
             BigDecimal latitude = receiveStatus.getLatitude();
             BigDecimal longitude = receiveStatus.getLongitude();
             String add = AmapUtil.getAdd(longitude+"", latitude+"");
             receiveStatus.setAddress(add);
         }
        return orderByOrderNo;
    }

    /**
     * 提交材料
     * */
    @Override
    public void submitData(AccompanyReceiveOrderDto accompanyReceiveOrderDto) {//接单编号  订单编号   经纬度
        if (BizEmpty(accompanyReceiveOrderDto.getData())){
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        //根据接单编号查询 有没有 提交
    AccompanyReceiveStatus accompanyReceiveStatus =    accompanyReceiveStatusMapper.getStatusByReceiveNo(accompanyReceiveOrderDto);
        if (!BizEmpty(accompanyReceiveStatus)){
            throw   new BizException(ApiResultCode.PLEASE_DO_NOT_SING);
        }
        //先查查
        //先看在不在这个位置
        Order order = new Order();
        order.setOrderNo(accompanyReceiveOrderDto.getOrderNo());
        OrderDto orderByOrderNo = orderMapper.getOrderByOrderNo(order);
        Integer hospitalDrugId = orderByOrderNo.getHospitalDrugId();
        Hospital hospital = new Hospital();
        hospital.setLongitude(accompanyReceiveOrderDto.getLongitude());
        hospital.setId(hospitalDrugId);
        hospital.setLatitude(accompanyReceiveOrderDto.getLatitude());
        List<HospitalDto> hospitalListByDistance = hospitalMapper.getHospitalListByDistance(hospital);
        HospitalDto hospitalDto = hospitalListByDistance.get(0);
        //比较经纬度
        if (!checkLocations(Double.parseDouble(hospitalDto.getLongitude()+""),Double.parseDouble(hospitalDto.getLatitude()+""),
                Double.parseDouble(accompanyReceiveOrderDto.getLongitude()+""),
                Double.parseDouble(accompanyReceiveOrderDto.getLatitude()+""),distance
                )){
            throw new BizException(ApiResultCode.LOCATION_NOT_SCOPE);
        }

        //根据接单编号 上传材料
        accompanyReceiveOrderMapper.updateByReceive(accompanyReceiveOrderDto);
        //修改接单状态 和订单状态
        OrderDto orderDto = new OrderDto();
        orderDto.setStartLongitude(accompanyReceiveOrderDto.getLongitude());
        orderDto.setStartLatitude(accompanyReceiveOrderDto.getLatitude());
        orderDto.setReceiveStatus(3);
        orderDto.setReceiveNo(accompanyReceiveOrderDto.getReceiveNo());
        updateStatusOrder(orderDto);


    }
    @Transactional
    public void updateStatusOrder(OrderDto orderDto){//订单编号  status
//        //订单编号 修改状态
//        orderMapper.updateStatusByorderNo(orderDto);
        //增加接单状态  根据接单编号
        AccompanyReceiveOrderDto accompanyReceiveOrderDto = new AccompanyReceiveOrderDto();
        accompanyReceiveOrderDto.setReceiveNo(orderDto.getReceiveNo());
        accompanyReceiveOrderDto.setStatus(orderDto.getReceiveStatus());
        accompanyReceiveOrderDto.setLongitude(orderDto.getStartLongitude());
        accompanyReceiveOrderDto.setLatitude(orderDto.getStartLatitude());
       accompanyReceiveStatusMapper.insertBinding(accompanyReceiveOrderDto);// 插入状态

    }

    /**
     * 经纬度比较
     * */
    public boolean checkLocations(double lng1, double lat1, double lng2, double lat2, Integer scope) {
        double distance = getDistance(lat1, lng1, lat2, lng2);
        return distance <= scope;

    }
    private static double EARTH_RADIUS = 6378.137;
    public static double getDistance(double lat1, double lng1, double lat2,
                                     double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000d) / 10000d;
        s = s * 1000;
        return s;
    }
    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }
/**
 * 服务结束
 * */
    @Transactional
    @Override
    public void serviceOver(AccompanyReceiveOrderDto accompanyReceiveOrder) {// 接单号 订单号 经纬度  录音
        if (BizEmpty(accompanyReceiveOrder.getRecording())){
            throw new BizException(ApiResultCode.COMMON_PARAM_NULL);
        }
        if (BizEmpty(accompanyReceiveOrder.getReceiveNo())){
            throw new BizException(ApiResultCode.COMMON_PARAM_NULL);
        }
        if (BizEmpty(accompanyReceiveOrder.getOrderNo())){
           throw new BizException(ApiResultCode.COMMON_PARAM_NULL);
        }
        if (BizEmpty(accompanyReceiveOrder.getLatitude())||BizEmpty(accompanyReceiveOrder.getLongitude())){
            throw new BizException(ApiResultCode.COMMON_PARAM_NULL);
        }

        //根据接单号 上传录音等数据
        accompanyReceiveOrderMapper.updateByReceive(accompanyReceiveOrder);
//     添加接单状态
        accompanyReceiveOrder.setStatus(4);
        accompanyReceiveStatusMapper.insertBinding(accompanyReceiveOrder);
        //修改订单状态
        OrderDto orderDto = new OrderDto();
        orderDto.setOrderNo(accompanyReceiveOrder.getOrderNo());
        orderDto.setStatus(4);
        orderMapper.updateStatusByorderNo(orderDto);
        //根据 orderNo 查询上级有没有人
        AccompanyAwardOrder accompanyAwardOrder =  new AccompanyAwardOrder();
        accompanyAwardOrder.setOrderNo(accompanyReceiveOrder.getOrderNo());
       AccompanyAwardOrder accompanyAwardOrder1 =  accompanyAwardOrderMapper.getAwardOrderByOrderNo(accompanyAwardOrder);
       if(!BizEmpty(accompanyAwardOrder1)){
           //给上级陪诊 流水状态改变 加钱
           PidAddMoney(accompanyAwardOrder1);

       }
        //给我自己的流水 状态改变加钱
        meMoney(accompanyReceiveOrder);

    }

    private void PidAddMoney(AccompanyAwardOrder accompanyAwardOrder1) {
        accompanyAwardOrder1.setStatus(0);
        //给上级加钱状态改为成功
        accompanyAwardOrderMapper.updateAwardStatus(accompanyAwardOrder1);
        AccompanyWalletRecode accompanyWalletRecode = new AccompanyWalletRecode();
        accompanyWalletRecode.setTransactionNo(accompanyAwardOrder1.getTransaction());
        accompanyWalletRecode.setStatus(0);
        accompanyWalletRecodeMapper.updateWalletByTransaction(accompanyWalletRecode);
        //把钱给上级加上
        AccompanyWallet accompanyWallet = new AccompanyWallet();
        accompanyWallet.setAccompanyId(accompanyAwardOrder1.getAccompanyPid());
        accompanyWallet.setMoney(new BigDecimal("5.00"));
        accompanyWalletMapper.updateMoney(accompanyWallet);
    }

    /**
   * 我的订单
   * */
    @Override
    public PageInfo<OrderDto> myOrder(Order order) {//陪诊id 和status
        PageHelper.startPage(pageUtils.getPage().getPageNum(),pageUtils.getPage().getPageSize());
    //根据陪诊id 查询所接订单
        if (!BizEmpty(order.getStatus())){
            Integer status = order.getStatus();
            if (status==1||status==6||status==7){
                throw  new BizException(ApiResultCode.COMMON_PARAM_INVALID);
            }
            if (status==2){
                List<OrderDto> orderDto  = orderMapper.getMyOrderByStatus1(order);
                return new PageInfo<>(orderDto);
            }else {
                List<OrderDto> orderDto=   orderMapper.getMyOrderByStatus(order);
                return new PageInfo<>(orderDto);
            }
        }else {
            List<OrderDto> orderDto=   orderMapper.getMyOrderByStatus(order);
            return new PageInfo<>(orderDto);
        }

    }
   /**
    * 联系用户
    * */
    @Override
    public Object userPhone(Order order) {//患者id
          //根据患者id查询患者姓名和电话
        Integer patientId = order.getPatientId();
        Relation relation =  new Relation();
        relation.setId(patientId);
        Relation familyByRelationId = relationMapper.getFamilyByRelationId(relation);
        return familyByRelationId;
    }
/**
 * 用户评价
 * */
    @Override
    public PageInfo<OrderComment> userEvaluate(Order order) {
        PageHelper.startPage(pageUtils.getPage().getPageNum(),pageUtils.getPage().getPageSize());
        //根据陪诊id 查找出所有的订单
        order.setStatus(5);
        OrderDto orderDto =  new OrderDto();
        List<String> orderNos  = new ArrayList<>();
        List<OrderDto> myOrderByStatus = orderMapper.getListOrderByStasusAndAccompanyid(order);
        for (OrderDto orderByStatus : myOrderByStatus) {
            orderNos.add(orderByStatus.getOrderNo());
        }List<OrderComment> orderComments = new ArrayList<>();
        if (orderNos.size()>0){
            orderDto.setOrderNos(orderNos);
            orderComments= orderCommentMapper.getEvaluateByOrderNo(orderDto);
        }

        return new PageInfo<>(orderComments);
    }

    /**
     * 生成加密数据
     * */
    @Override
    public Object QRCode() throws Exception {
        String userId = commonUtil.getUserId(request);
        UserAccompany userAccompany = new UserAccompany();
        userAccompany.setUid(Integer.parseInt(userId));
        UserAccompany accompanyByUid = accompanyMapper.getAccompanyByUid(userAccompany);
        if (BizEmpty(accompanyByUid)){
            throw new BizException(ApiResultCode.NOT_ACCOMPANY);
        }
        String encrypt = encrypt(password, userId);
        return encrypt;
    }
  /**
   * 解密
   * */
    @Override
    public void decode(String decode) throws Exception {
        //首先看看我是不是陪诊
        //找到这个陪诊id 后  绑定
        UserAccompany userAccompany = new UserAccompany();

        String userId1 = commonUtil.getUserId(request);//本人的userid
        userAccompany.setUid(Integer.parseInt(userId1));
        UserAccompany accompanyByUid1 = accompanyMapper.getAccompanyByUid(userAccompany);
         if (!BizEmpty(accompanyByUid1)){
             throw new BizException(ApiResultCode.ALREADY_EXIST);
         }
         //再去查询我有没有上级
        AccompanyInvite accompanyInvite1 = new AccompanyInvite();
         accompanyInvite1.setUid(Integer.parseInt(userId1));
        AccompanyInvite accompanyInvite2 = accompanyInviteMapper.getaccompanyPid(accompanyInvite1);
        if (!BizEmpty(accompanyInvite2)){
            throw new BizException(ApiResultCode.ALREADY_BINDING);
        }
        String userId = decrypt(password, decode);//userId
        //根据userid查看这个人的陪诊id

        userAccompany.setUid(Integer.parseInt(userId));
        UserAccompany accompanyByUid = accompanyMapper.getAccompanyByUid(userAccompany);
        if (BizEmpty(accompanyByUid)){
            throw new BizException(ApiResultCode.DATA_NOT_EXIST);
        }

        AccompanyInvite accompanyInvite = new AccompanyInvite();
        accompanyInvite.setUid(Integer.parseInt(userId1));
        accompanyInvite.setAccompanyId(accompanyByUid.getAccompanyId());
        accompanyInvite.setStatus(1);
        accompanyInviteMapper.insertPid(accompanyInvite);
    }
 /**
  * 接单状态
  * */
    @Transactional
    @Override
    public Object orderReceivingStatus(OrderDto orderDto) {//订单编号经纬度 status 1 2
        //根据订单编号查询订单详情
        OrderDto orderByOrderNo = orderMapper.getOrderByOrderNo(orderDto);
        if (BizEmpty(orderByOrderNo)){
            throw  new BizException(ApiResultCode.NOT_ORDER);
        }
        //看看我有没有接单

        //先查询有没有过打卡记录   根据订单编号和  status 1  2
      List<AccompanyReceiveStatus> accompanyReceiveStatuses=  accompanyReceiveStatusMapper.selectARSByOrderNoAndStatus(orderDto);
        for (AccompanyReceiveStatus accompanyReceiveStatus : accompanyReceiveStatuses) {
            Integer status = accompanyReceiveStatus.getStatus();
            if (status==orderDto.getStatus()){
                throw  new BizException(ApiResultCode.PLEASE_DO_NOT_SING);
            }
        }

        //查询接单编号
        AccompanyReceiveOrder receiveByOrderNo = accompanyReceiveOrderMapper.getReceiveByOrderNo(orderByOrderNo);

        if (orderDto.getStatus()==1){
            Insurance insurance = new Insurance();
            insurance.setOrderNo(orderDto.getOrderNo());
         Insurance insurance1=    insuranceMapper.getInsuranceByOrderNo(insurance);
         if (BizEmpty(insurance1)){
             insuranceService.Insurance(insurance);
         }
            //到用户家里
            BigDecimal startLatitude = orderByOrderNo.getStartLatitude();//出发纬度
            BigDecimal startLongitude = orderByOrderNo.getStartLongitude();//出发经度
            if (!checkLocations(Double.parseDouble(startLongitude+""),Double.parseDouble(startLatitude+""),
                   Double.parseDouble(orderDto.getStartLongitude()+""),Double.parseDouble(orderDto.getStartLatitude()+""),
                    distance
                    ))
            {
                throw new BizException(ApiResultCode.LOCATION_NOT_SCOPE);
            }
            //修改订单表状态
            OrderDto orderDto1 = new OrderDto();
            orderDto1.setStatus(3);
            orderDto1.setOrderNo(orderDto.getOrderNo());
            orderMapper.updateStatusByorderNo(orderDto1);
        }

        if (orderDto.getStatus()==2){
            Integer hospitalDrugId = orderByOrderNo.getHospitalDrugId();
            Hospital hospital =  new Hospital();
            hospital.setId(hospitalDrugId);
            hospital.setLatitude(orderDto.getStartLatitude());
            hospital.setLongitude(orderDto.getStartLongitude());
            List<HospitalDto> hospitalListByDistance = hospitalMapper.getHospitalListByDistance(hospital);
            HospitalDto hospitalDto = hospitalListByDistance.get(0);
            BigDecimal hospitallatitude = hospitalDto.getLatitude();//医院纬度
            BigDecimal hospitallongitude = hospitalDto.getLongitude();//医院经度
            if (!checkLocations(Double.parseDouble(hospitallongitude+""),Double.parseDouble(hospitallatitude+""),
                    Double.parseDouble(orderDto.getStartLongitude()+""),Double.parseDouble(orderDto.getStartLatitude()+""
                    ),distance)){
                throw new BizException(ApiResultCode.LOCATION_NOT_SCOPE);
            }
        }

        //打完卡 增加状态
        AccompanyReceiveOrderDto accompanyReceiveOrderDto = new AccompanyReceiveOrderDto();
        accompanyReceiveOrderDto.setReceiveNo(receiveByOrderNo.getReceiveNo());
        accompanyReceiveOrderDto.setStatus(orderDto.getStatus());
        accompanyReceiveOrderDto.setLongitude(orderDto.getStartLongitude());
        accompanyReceiveOrderDto.setLatitude(orderDto.getStartLatitude());
        accompanyReceiveStatusMapper.insertBinding(accompanyReceiveOrderDto);
        return "ok";
    }

    private void meMoney(AccompanyReceiveOrderDto accompanyReceiveOrder) {
       // int i = 1/0;
        //给自己钱包加钱 流水账单
        //先查出此单超出的价格 平分
        Order order = new Order();
        order.setOrderNo(accompanyReceiveOrder.getOrderNo());
        OrderDto orderByOrderNo = orderMapper.getOrderByOrderNo(order);
        BigDecimal exceed = orderByOrderNo.getExceed();
        BigDecimal exceed1 = exceed.divide(new BigDecimal(2),2,BigDecimal.ROUND_HALF_UP);//超出价格的一半

        //查询这个订单的价格
        BigDecimal accompanyMoney = orderByOrderNo.getAccompanyMoney();

        //再去查陪诊的加价价格
        Integer accompanyId = orderByOrderNo.getAccompanyId();
        UserAccompany  userAccompany = new UserAccompany();
        userAccompany.setAccompanyId(accompanyId);
       UserAccompany userAccompany1 = accompanyMapper.getAccompanyByPid(userAccompany);
        BigDecimal unitPrice = userAccompany1.getUnitPrice();//陪诊加价价格
        BigDecimal accompany = exceed1.add(accompanyMoney).add(unitPrice);
        AccompanyWallet accompanyWallet = new AccompanyWallet();
        accompanyWallet.setAccompanyId(accompanyId);
        accompanyWallet.setMoney(accompany);
        accompanyWalletMapper.updateMoney(accompanyWallet);
        //修改钱包流水记录status为0 //根据接单编号
        AccompanyWalletRecode accompanyWalletRecode = new AccompanyWalletRecode();
        accompanyWalletRecode.setTransactionNo(accompanyReceiveOrder.getReceiveNo());
        accompanyWalletRecode.setStatus(0);
        accompanyWalletRecodeMapper.updateWalletByTransaction(accompanyWalletRecode);
//        Integer id = accompanyWallet.getId();//本账户钱包id
//
//        accompanyWalletRecode.setMoney(accompany);
//        accompanyWalletRecode.setTransactionNo(accompanyReceiveOrder.getReceiveNo());
//        accompanyWalletRecode.setType(1);
//        accompanyWalletRecode.setStatus(0);
//        accompanyWalletRecode.setWalletId(id);
//        accompanyWalletRecodeMapper.insertWalletByWalletId(accompanyWalletRecode);
    }

    //上级操作
    private void superiorOperate(AccompanyInvite accompanyAwardOrderInfo,AccompanyReceiveOrder accompanyReceiveOrder) {
        //插入奖励订单 五块一单
        Integer accompanyId = accompanyAwardOrderInfo.getAccompanyId();//上级陪诊
//        Integer uid = accompanyAwardOrderInfo.getUid();//陪诊id
//        AccompanyAwardOrder accompanyAwardOrder = new AccompanyAwardOrder();
//        accompanyAwardOrder.setAccompanyId(uid);//本单陪诊id
//        accompanyAwardOrder.setAccompanyPid(accompanyId);//上级陪诊id
//        accompanyAwardOrder.setOrderNo(accompanyReceiveOrder.getOrderNo());//订单编号

//        accompanyAwardOrder.setTransaction(transaction);
//        accompanyAwardOrder.setMoney(new BigDecimal(5.0));
//        //给 上级陪诊人员加钱
//        AccompanyWallet accompanyWallet = new AccompanyWallet();
//        //插入数据
//        accompanyAwardOrderMapper.insertAwardOrder(accompanyAwardOrder);
//        accompanyWalletMapper.updateMoney(accompanyWallet);
        BigDecimal money = new BigDecimal("5.00");
        AccompanyWallet accompanyWallet = new AccompanyWallet();
        accompanyWallet.setMoney(money);
        accompanyWallet.setAccompanyId(accompanyId);
        String transaction = commonUtil.getWasteNumber();//生成交易号
        //给上级陪诊加流水
        //查询上级陪诊的钱包
        AccompanyWallet moneySum = accompanyWalletMapper.getMoneySum(accompanyWallet);
        Integer id = moneySum.getId();//钱包id
        AccompanyWalletRecode accompanyWalletRecode = new AccompanyWalletRecode();
        accompanyWalletRecode.setWalletId(id);
        accompanyWalletRecode.setTransactionNo(transaction);
        accompanyWalletRecode.setMoney(money);
        accompanyWalletRecode.setStatus(1);
        accompanyWalletRecode.setType(2);
        accompanyWalletRecodeMapper.insertWalletByWalletId(accompanyWalletRecode);
        //陪诊奖励订单插入
          AccompanyAwardOrder accompanyAwardOrder =  new AccompanyAwardOrder();
          accompanyAwardOrder.setOrderNo(accompanyReceiveOrder.getOrderNo());//订单号
          accompanyAwardOrder.setTransaction(transaction);//交易号
          accompanyAwardOrder.setStatus(1);//进行中
          accompanyAwardOrder.setMoney(money);//金额
          accompanyAwardOrder.setAccompanyId(accompanyReceiveOrder.getAccompanyId());//陪诊id
          accompanyAwardOrder.setAccompanyPid(accompanyId);//上级陪诊id
         accompanyAwardOrderMapper.insertAwardOrder(accompanyAwardOrder);

    }

    //查询账号状态
     public ApiResult<Object> getUserStatus(TUser tUser){//uid
         UserAccompany userAccompany = tUserMappers.getAccompanyInfoByUid(tUser);

//         if (BizEmpty(userAccompany)){
//             throw new BizException(ApiResultCode.NOT_ACCOMPANY);
//         }
//         if (userAccompany.getStatus()==1){
//             throw new BizException(ApiResultCode.UNDER_REVIEW);
//         }
//         if (userAccompany.getStatus()==2){
//             throw new BizException(ApiResultCode.AUDIT_FAILURE);
//         }
//         if (userAccompany.getWorkStatus()==1){
//             throw new BizException(ApiResultCode.FREEZE);
//         }
         return ApiResult.newSuccess(userAccompany);
     }
}
